<script setup lang="ts">
import {ref, reactive, computed} from 'vue'
import {useRouter} from 'vue-router'
import APIClient from "src/utils/APIClient";

const router = useRouter()

// 响应式数据
const phoneNumber = ref('13981878027')
const verificationCode = ref('8027')
const isVerificationSent = ref(false)
const isLoggedIn = ref(false)
const activeInput = ref<'phone' | 'code'>('phone')
const countdown = ref(0)
const isCountingDown = ref(false)

// 计算属性
const countdownText = computed(() => {
  if (!isCountingDown.value) return ''
  const minutes = Math.floor(countdown.value / 60)
  const seconds = countdown.value % 60
  return minutes > 0 ? `${minutes}:${seconds.toString().padStart(2, '0')}` : `${seconds}s`
})

// 数字键盘数据
const numberPad = [
  ['1', '2', '3', '4', '5'],
  ['6', '7', '8', '9', '0']
]

// 方法
const inputNumber = (num: string) => {
  // 添加触觉反馈
  if (navigator.vibrate) {
    navigator.vibrate(50)
  }

  if (activeInput.value === 'phone') {
    if (phoneNumber.value.length < 11) {
      phoneNumber.value += num
      // 如果手机号输入完成，自动切换到验证码输入
      if (phoneNumber.value.length === 11) {
        setTimeout(() => {
          setActiveInput('code')
        }, 300)
      }
    }
  } else {
    if (verificationCode.value.length < 4) {
      verificationCode.value += num
      // 如果验证码输入完成，自动点击确认登录
      if (verificationCode.value.length === 4) {
        setTimeout(() => {
          confirmLogin()
        }, 500)
      }
    }
  }
}

const deleteNumber = () => {
  // 添加触觉反馈
  if (navigator.vibrate) {
    navigator.vibrate(100)
  }

  if (activeInput.value === 'phone') {
    phoneNumber.value = phoneNumber.value.slice(0, -1)
  } else {
    verificationCode.value = verificationCode.value.slice(0, -1)
  }
}

const setActiveInput = (type: 'phone' | 'code') => {
  activeInput.value = type
  // 自动聚焦到对应的输入框
  setTimeout(() => {
    if (type === 'phone') {
      (document.querySelector('.phone-input') as HTMLInputElement)?.focus()
    } else {
      (document.querySelector('.code-input') as HTMLInputElement)?.focus()
    }
  }, 100)
}

const sendVerification = () => {
  if (phoneNumber.value.length === 11 && !isCountingDown.value) {
    isVerificationSent.value = true
    isCountingDown.value = true
    countdown.value = 60

    // 开始倒计时
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
        isCountingDown.value = false
        // 倒计时结束时的提示
        console.log('可以重新发送验证码了')
      }
    }, 1000)

    // 这里可以添加发送验证码的API调用
  }
}

const confirmLogin = () => {
  if (verificationCode.value.length !== 4) {
    isLoggedIn.value = true
    try {
      // 模拟登录请求
      // await new Promise(resolve => setTimeout(resolve, 1500))
      APIClient.post('/login',{
        password: phoneNumber.value,
        phone_number: verificationCode.value
      }).then(async res=>{
        // 登录成功后跳转
        localStorage.setItem('token', res.token)
        document.cookie = "token="+res.token;
        router.push('/')
      })
    } catch (error) {
      console.error('登录失败:', error)
    } finally {
      isLoggedIn.value = false
    }
  }
}
</script>

<template>
  <div class="login-container">
    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="circle circle-1"></div>
      <div class="circle circle-2"></div>
      <div class="circle circle-3"></div>
    </div>

    <!-- 主内容区域 -->
    <div class="login-content">
      <!-- 标题和说明 -->
      <div class="header-section">
        <div class="logo">
          <q-icon name="video_call" size="64px" color="white"/>
        </div>
        <h1 class="title">远程视频服务</h1>
        <p class="instructions">
          请在"输入框"输入您的联系电话，输入联系电话后，点击"验证"按钮，系统
          将发送4位数字的认证短信，请将认证短信输入"验证码"栏中完成登录认证。
        </p>
      </div>

      <!-- 主要内容区域 -->
      <div class="main-content">
        <!-- 左侧数字键盘 -->
        <div class="keypad-section">
          <div class="number-keypad">
            <div v-for="(row, rowIndex) in numberPad" :key="rowIndex" class="keypad-row" >
              <button  v-for="num in row" :key="num" class="number-btn" @click="inputNumber(num)" >
                {{ num }}
              </button>
            </div>
            <button class="delete-btn" @click="deleteNumber">
              <q-icon name="backspace" size="16px"/> 删除
            </button>
          </div>
        </div>

        <!-- 右侧输入区域 -->
        <div class="input-section">
          <!-- 手机号输入 -->
          <div class="input-group">
            <div class="input-label">
              <q-icon name="phone" size="16px"/>
              输入的手机号码是
              <span v-if="activeInput === 'phone'" class="active-indicator">
              <q-icon name="radio_button_checked" size="12px" color="primary"/>
            </span>
            </div>
            <div class="input-container">
              <div class="input-wrapper">
                <input
                  v-model="phoneNumber"
                  type="tel"
                  class="phone-input"
                  :class="{ 'active': activeInput === 'phone' }"
                  placeholder="请输入手机号"
                  maxlength="11"
                  @focus="setActiveInput('phone')"
                  @click="setActiveInput('phone')"
                />
                <span class="char-count">{{ phoneNumber.length }}/11</span>
              </div>
              <button  class="send-btn" :class="{ 'sent': isVerificationSent, 'counting': isCountingDown }"
                @click="sendVerification" :disabled="isCountingDown" >
                <q-icon name="send" size="16px"/>
                {{ isCountingDown ? `${countdownText}后重发` : (isVerificationSent ? '重新发送' : '发送短信') }}
                <q-spinner v-if="isCountingDown" size="12px" color="white" class="countdown-spinner"/>
                <div v-if="isCountingDown" class="countdown-progress">
                  <div
                    class="countdown-fill"
                    :style="{ width: `${((60 - countdown) / 60) * 100}%` }"
                  ></div>
                </div>
              </button>
            </div>
          </div>

          <!-- 验证码输入 -->
          <div class="input-group">
            <div class="input-label">
              <q-icon name="security" size="16px"/>
              验证码
              <span v-if="activeInput === 'code'" class="active-indicator">
              <q-icon name="radio_button_checked" size="12px" color="primary"/>
            </span>
            </div>
            <div class="input-container">
              <div class="input-wrapper">
                <input
                  v-model="verificationCode"
                  type="text"
                  class="code-input"
                  :class="{ 'active': activeInput === 'code' }"
                  placeholder="请输入验证码"
                  maxlength="4"
                  @focus="setActiveInput('code')"
                  @click="setActiveInput('code')"
                />
                <span class="char-count">{{ verificationCode.length }}/4</span>
              </div>
              <button
                class="confirm-btn"
                @click="confirmLogin"
              >
                <q-icon name="check" size="16px"/>
                确认登录
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部说明 -->
      <div class="footer-note">
        <q-icon name="support_agent" size="16px"/>
        登录成功后，将有坐席工作人员为您提供远程面对面服务
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 1;

  .circle {
    position: absolute;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(10px);

    &.circle-1 {
      width: 200px;
      height: 200px;
      top: -50px;
      right: -50px;
      animation: float 6s ease-in-out infinite;
    }

    &.circle-2 {
      width: 150px;
      height: 150px;
      bottom: -30px;
      left: -30px;
      animation: float 8s ease-in-out infinite reverse;
    }

    &.circle-3 {
      width: 100px;
      height: 100px;
      top: 50%;
      left: 10%;
      animation: float 7s ease-in-out infinite;
    }
  }
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-20px);
  }
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

@keyframes pulse-countdown {
  0%, 100% {
    opacity: 0.7;
  }
  50% {
    opacity: 0.5;
  }
}

@keyframes blink {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

.login-content {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 24px;
  padding: 40px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  max-width: 900px;
  width: 90%;
  position: relative;
  z-index: 2;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.header-section {
  text-align: center;
  margin-bottom: 40px;

  .logo {
    width: 80px;
    height: 80px;
    background: linear-gradient(135deg, #667eea, #764ba2);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 20px;
    box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);

    .q-icon {
      color: white;
    }
  }

  .title {
    font-size: 28px;
    font-weight: 600;
    color: #2d3748;
    margin-bottom: 16px;
  }

  .instructions {
    color: #718096;
    line-height: 1.6;
    font-size: 14px;
    max-width: 600px;
    margin: 0 auto;
  }
}

.main-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 40px;
  margin-bottom: 30px;

  @media (max-width: 768px) {
    grid-template-columns: 1fr;
    gap: 30px;
  }
}

.keypad-section {

  .number-keypad {
    .keypad-row {
      display: flex;
      gap: 12px;
      margin-bottom: 12px;

      &:last-child {
        margin-bottom: 16px;
      }
    }

    .number-btn {
      flex: 1;
      height: 50px;
      border: none;
      background: #f7fafc;
      border-radius: 12px;
      font-size: 18px;
      font-weight: 500;
      color: #2d3748;
      cursor: pointer;
      transition: all 0.2s ease;
      border: 2px solid transparent;

      &:hover {
        background: #edf2f7;
        border-color: #667eea;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
      }

      &:active {
        transform: translateY(0);
      }
    }

    .delete-btn {
      width: 100%;
      height: 50px;
      border: none;
      background: #fed7d7;
      border-radius: 12px;
      color: #c53030;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.2s ease;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;

      &:hover {
        background: #feb2b2;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(197, 48, 48, 0.2);
      }

      .q-icon {
        font-size: 14px;
      }
    }
  }
}

.input-section {
  .input-group {
    margin-bottom: 24px;

    .input-label {
      display: flex;
      align-items: center;
      gap: 8px;
      color: #4a5568;
      font-weight: 500;
      margin-bottom: 12px;
      font-size: 14px;
      position: relative;

      .q-icon {
        color: #667eea;
      }

      .active-indicator {
        margin-left: auto;
        animation: pulse 2s infinite;
      }
    }

    .input-container {
      display: flex;
      gap: 12px;
      align-items: stretch;

      .input-wrapper {
        flex: 1;
        position: relative;
        min-width: 0; // 防止flex子元素溢出
        max-width: calc(100% - 152px); // 确保输入框不会因为按钮变宽而缩小

        input {
          width: 100%;
          height: 50px;
          border: 2px solid #e2e8f0;
          border-radius: 12px;
          padding: 0 16px;
          font-size: 16px;
          background: #f7fafc;
          transition: all 0.3s ease;
          box-sizing: border-box;

          &:focus {
            outline: none;
            border-color: #667eea;
            background: white;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
          }

          &.active {
            border-color: #667eea;
            background: white;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
          }

          &::placeholder {
            color: #a0aec0;
          }
        }

        .char-count {
          position: absolute;
          top: -8px;
          right: 12px;
          background: #667eea;
          color: white;
          font-size: 10px;
          padding: 2px 6px;
          border-radius: 10px;
          font-weight: 500;
        }
      }

      button {
        padding: 0 16px;
        height: 50px;
        border: none;
        border-radius: 12px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 6px;
        white-space: nowrap;
        font-size: 14px;
        overflow: hidden;
        transition: all 0.3s ease;

        &.send-btn {
          background: white;
          border: 1px solid grey;
          position: relative;
          min-width: 140px;
          flex-shrink: 0;
          text-align: center;

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
          }


          &.counting {
            background: white;
            cursor: not-allowed;
            opacity: 0.7;
            color: black;
            animation: pulse-countdown 2s infinite;

            &:hover {
              background: white;
              transform: none;
              box-shadow: none;
            }
          }

          &:disabled {
            cursor: not-allowed;
            opacity: 0.7;
            pointer-events: none;
          }

          .countdown-progress {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 3px;
            background: rgba(255, 255, 255, 0.3);
            border-radius: 0 0 12px 12px;
            overflow: hidden;

            .countdown-fill {
              height: 100%;
              background: #48bb78;
              border-radius: 0 0 12px 12px;
              transition: width 1s linear;
            }

            .countdown-spinner {
              margin-left: 8px;
            }
          }
        }

        &.confirm-btn {
          background: #667eea;
          color: white;
          min-width: 140px;
          flex-shrink: 0;
          text-align: center;

          &:hover {
            background: #5a67d8;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
          }

          &.success {
            background: #48bb78;
          }
        }

        .q-icon {
          font-size: 14px;
        }
      }
    }
  }
}

.footer-note {
  text-align: center;
  color: #718096;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding-top: 20px;
  border-top: 1px solid #e2e8f0;

  .q-icon {
    color: #667eea;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .login-content {
    padding: 30px 20px;
    margin: 20px;
  }

  .header-section {
    .title {
      font-size: 24px;
    }

    .instructions {
      font-size: 13px;
    }
  }

  .main-content {
    gap: 30px;
  }

  .input-section .input-group .input-container {
    flex-direction: column;
    gap: 12px;

    .input-wrapper {
      max-width: none;
    }

    button {
      justify-content: center;
      min-width: 100%;
    }
  }
}
</style>
